<?php namespace App\Models;

use App\Models\ProductCategory;

class Product extends \Eloquent
{
	protected $table = "products";
	protected $softDelete = true;

	public function categories()
	{
		return $this->belongsToMany("App\Models\ProductCategory", "products_product_categories", "productid", "categoryid");
	}
	
	public function attributes()
	{
		return $this->belongsToMany("App\Models\ProductAttribute", "product_product_attributes", "productid", "productattributeid")->withPivot("content")->withTimestamps();
	}

	public function packaging()
	{
		$attributes = $this->belongsToMany("App\Models\ProductAttribute", "product_product_attributes", "productid", "productattributeid")->withPivot("content")->get();
		foreach ($attributes as $attribute) {
			if(trim(strtolower($attribute->attributename)) == "packaging")
			{
				return $attribute->pivot->content;
			}
		}

		return "";
	}
	
	public function images()
	{
		return $this->belongsToMany("App\Models\ProductImage", "product_product_images", "productid", "imageid")->withTimestamps();
	}
	
	public function files()
	{
		return $this->belongsToMany("App\Models\ProductFile", "product_product_files", "productid", "fileid")->withTimestamps();
	}
	
	public function relatedproducts()
	{
		return $this->belongsToMany("App\Models\Product", "product_related_products", "productid", "relatedproductid")->withPivot("displayorder")->take(3)->orderBy('displayorder')->withTimestamps();
	}
	
	public function unrelatedproducts()
	{
		$ids = \DB::table('product_related_products')->where('productid', '=', $this->id)->lists('relatedproductid');
		
		return Product::whereNotIn('id', (count($ids) == 0?array($this->id):$ids))->where("id","!=", $this->id);
		
	}
	
}